#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年9月15日

@author: chenyongbing
'''
import sys,os,commands,re
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]
import logging

'''
    add git tag
'''

from build_project import BuildProject

myBuildProject = BuildProject()




def get_branch_and_commit(projectPath = '/data/zhimind/2015-09-16/zm-ws-v3.0916',gitPath = '/home/zhima/java/build',tag=None,delete=False):
    if tag==None:
        tag = re.sub('^/|/$','',projectPath).split('/')[-1]
    
    
    
    
    
    rfile = projectPath+'/README'
    if not os.path.exists(rfile):
        logging.error('file %s not exists.'%(rfile))
        sys.exit()

    for line in open(rfile).read().split('\n'):
        lineList = line.split(',')
        if len(lineList)!=3:continue
        pj_name,pj_ver,pj_commit = lineList
        logging.info('%s,%s,%s'%(pj_name,pj_ver,pj_commit))
        if pj_name == 'zm-base':
            pj_gitpath = gitPath + '/%s-%s'%(pj_name,pj_ver)
        else:
            pj_gitpath = gitPath +'/%s'%pj_name
        
        os.chdir(pj_gitpath)
        pj_commit = re.sub('^commit\s*','',pj_commit)
        
        myBuildProject.git_pull()
        if pj_commit!=None:
            myBuildProject.git_checkout(pj_commit)
        else:
            logging.error('commit must not None')
            sys.exit()
        
        if delete == False:
            add_tag_cmd = 'git tag %s'%tag
            logging.info(add_tag_cmd)
            commands.getoutput(add_tag_cmd)
            
            add_tag_commit_cmd = 'git push  --tags'
            commands.getoutput(add_tag_commit_cmd)
        else:
            delete_tag = 'git push origin --delete tag %s'%tag
            commands.getoutput(delete_tag)



if __name__=='__main__':
    import argparse
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--tag',metavar="标签",default=None)
    parser.add_argument('-p',metavar="项目地址",required=True)
    parser.add_argument('--delete',action='store_true',help='delete tag')
    logging.basicConfig(level = logging.INFO)
    
    args = parser.parse_args()
    
    
    tag = args.tag
    projectPath = args.p
    delete = args.delete
    
    
    gitPath = '/home/zhima/java/build'
    
    get_branch_and_commit(projectPath=projectPath,gitPath=gitPath,delete=delete,tag=tag)
    
    
    